package edu.auctionmart

import edu.auctionmart.User

class LocationController {

	def authenticateService
    def scaffold = false
	
    def index() { 
		redirect(action: list)
	}
	
	def create = {
		def userInstance = User.findById(params.id)		
		def locationInstance = new Location()
		locationInstance.name = userInstance.userRealName
		render (view: 'create', model: [locationInstance: locationInstance, userInstance: userInstance])
	}
	
	def save = {
		def userInstance = User.findById(params.userId)
		
		def location = new Location(params)
		location.name = userInstance.userRealName
		
		if (location.validate()) {
			def profile = userInstance.profile
			if (profile) {
				profile.addToAddresses(location)
			} else {
				userInstance.profile = new Profile()
				profile = userInstance.profile
			}
			profile.addToAddresses(location)	
			profile.save()
				
			flash.message = "Successfully created new Location for ${userInstance.username}"
			redirect(controller: 'user', action:'myAccount', model: [userInstance: userInstance])	
		}
		render (view: 'create', model: [locationInstance: location, userInstance: userInstance])
	}
	
	def edit = {
		def locationInstance = Location.findById(params.id)
		if (!locationInstance) {
			flash.message = "Location not found with id $params.id"
			redirect action: list
			return
		}
		
		[locationInstance: locationInstance]
	}
	
	def update = {
		
		def principal = authenticateService.principal()
		String name = principal.getUsername()
		def userInstance = User.findByUsername(name)
						
		def location = Location.get(params.id)
		if (!location) {
			flash.message = "Location not found with id $params.id"
			render view: 'edit', model: [locationInstance: location]
			return
		}

		long version = params.version.toLong()
		if (location.version > version) {
			location.errors.rejectValue 'version', "location.optimistic.locking.failure",
				"Another location has updated this Location while you were editing."
				render view: 'edit', model: [locationInstance: location]
			return
		}

		location.properties = params
		
		if (location.save()) {
			flash.message = "Successfully edited Location for ${userInstance.username}"
			redirect(controller: 'user', action:'myAccount', model: [userInstance: userInstance])	
		}
		else {
			render view: 'edit', model: [locationInstance: location]
		}
	}
	
	def delete = {
		
		def principal = authenticateService.principal()
		String name = principal.getUsername()
		def userInstance = User.findByUsername(name)
		
		def location = Location.get(params.id)
		if (location) {
			userInstance.profile.removeFromAddresses(location)
			location.delete()
			flash.message = "Location deleted successfully for ${userInstance.username}"
		}
		else {
			flash.message = "Location not found with id $params.id"
		}
		redirect(controller: 'user', action:'myAccount', model: [userInstance: userInstance])	
	}
}
